package com.example.common.rc.aop.dicttrans.dictaop;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.common.core.CommonConstant;
import com.example.common.core.Result;
import com.example.common.rc.aop.dicttrans.classutil.ByteBuddyUtil;
import com.example.common.util.RefUtil;
import com.example.crud.sys.api.CommonAPI;
import com.example.crud.sys.model.DictModel;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * dict aop4
 *
 * @author zjarlin
 * @since 2023/03/25
 */
@Aspect
@Component
@Slf4j
@SuppressWarnings("all")
public class DictAop5 {

    @Autowired
    ObjectMapper objectMapper;

    Map<Class<?>, BiFunction<Object, Function<Object, ?>, ?>> operation = new HashMap<Class<?>, BiFunction<Object, Function<Object, ?>, ?>>() {{

        put(IPage.class, (outVO, translater) -> {
            IPage ipage = (IPage) outVO;
            List records = ipage.getRecords();
            return ipage.setRecords((List<Object>) records.stream().map(translater).collect(Collectors.toList()));
        });
        put(List.class, (outVO, translater) -> {
            List records = (List) outVO;
            return records.stream().map(translater).collect(Collectors.toList());
        });
        put(String.class, (outVO, translater) -> {
            String str = (String) outVO;
            return translater.apply(str);
        });
    }};

    /**
     * 实体上带有注解的翻译成中文
     * 使用了字节码技术新的返回对象其实是obj的子类
     *
     * @param obj 记录
     */

    @Autowired
    private CommonAPI commonAPI;

    @Pointcut("execution(* com.example..BaseController.*(..))")
    public void p1() {
    }

    @Pointcut("execution(* com.example..*Controller+.*(..))")
    public void p2() {
    }

    @Pointcut("execution(* com.example..*Api+.*(..))")
    public void p3() {
    }

    /**
     * 该切面会对实体中属性加了@DictCode2Name注解的字段生效,支持嵌套List<T>属性 T中加了注解的也会被翻译
     * Result<?>对于包装内里的类型,改变内容,aop源码中会对最外层包装类进行类型强转(Result<?>),不会报错
     *
     * @param pjp           pjp
     * @param needTransLate 需要翻译
     * @return {@link Object }
     * @author zjarlin
     * @since 2023/01/05
     */
    @Around("(p1()||p2()||p3()) &&  @annotation(needTransLate)")
    @SneakyThrows
    public Object transLateDict(ProceedingJoinPoint pjp, NeedTransLate needTransLate) {
        Object outVO = pjp.proceed();
        Class<?> aClass = outVO.getClass();

        if (String.class.isAssignableFrom(aClass)) {
            //单属性String翻译
            return extractSingleAttributeTranslation((String) outVO, needTransLate.dicCode(), needTransLate.tab(), needTransLate.codeColumn(), needTransLate.nameColumn(), needTransLate.isMulti());
        }

        if (outVO instanceof Result) {
            Result result = (Result) outVO;
            Object outVORes = result.getResult();
            Class<?> aClass1 = outVORes.getClass();
            //包装类型拆一层即为非包装类型,进行模式匹配
            BiFunction<Object, Function<Object, ?>, ?> consumerByType = patternMatching(aClass1);
            //BiFunction<Object, Function<Object, ?>, ?> consumerByType = PatternMatching.getConsumerByType(aClass);
            if (Objects.nonNull(consumerByType)) {
                Object apply = consumerByType.apply(outVORes, this::transOutVO);
                result.setResult(apply);
                return result;
            }
            result.setResult(this.transOutVO(outVORes));
            return result;
        }
        //走到这就是各种非包装类型的,进行模式匹配
        BiFunction<Object, Function<Object, ?>, ?> consumerByType = patternMatching(aClass);

        //BiFunction<Object, Function<Object, ?>, ?> consumerByType = PatternMatching.getConsumerByType(aClass);
        if (Objects.nonNull(consumerByType)) {
            Object apply = consumerByType.apply(outVO, this::transOutVO);
            return apply;
        }
        //走到这就是只返回实体类型的
        Object o = this.transOutVO(outVO);
        return o;
    }

    //@Lazy

    private BiFunction<Object, Function<Object, ?>, ?> patternMatching(Class<?> aClass) {
        return operation.entrySet().stream().filter(op -> op.getKey().isAssignableFrom(aClass)).map(Map.Entry::getValue).findAny().orElse(null);
    }

    @SneakyThrows
    private Object transOutVO(Object obj) {
        Class<?> aClass = obj.getClass();
        /*
        SerializerFeature.WriteMapNullValue--->   null值也展示
        Feature.OrderedField---> 按照实体中的字段排序
        */
//        objectMapper.enable(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS);
//        objectMapper.enable(SerializationFeature.WRITE_NULL_MAP_VALUES);

//        String json = objectMapper.writeValueAsString(obj);
//        JSONObject jsonObject = JSON.parseObject(json, Feature.OrderedField, Feature.SupportArrayToBean);

        Field[] declaredFields = aClass.getDeclaredFields();
        if (ArrayUtil.isEmpty(declaredFields)) {
            return obj;
        }
        //需要添加的字段
        //List<String> collect = Arrays.stream(declaredFields).filter(field -> {
        //    Object fieldValue = ReflectUtil.getFieldValue(obj, field);
        //    boolean annotationPresent = field.isAnnotationPresent(DictCode2Name.class);
        //    boolean nonNull = Objects.nonNull(fieldValue);
        //    return annotationPresent && nonNull;
        //}).map(e -> {
        //    DictCode2Name annotation1 = e.getAnnotation(DictCode2Name.class);
        //    String s = annotation1.deserializeAlias();
        //    String s1 = StrUtil.toCamelCase(annotation1.nameColumn());
        //    String other = e.getName() + CommonConstant.DICT_TEXT_SUFFIX;
        //    String s2 = StrUtil.firstNonBlank(s, s1, other);
        //    return s2;
        //}).collect(Collectors.toList());

        Map<String, List<DictCode2Name>> annoMap = RefUtil.findAnnoMap(aClass, DictCode2Name.class, DictCode2Names.class, DictCode2Names::value);

        //需要增加的字段
        List<String> collect = annoMap.entrySet().stream().flatMap(e -> {
            String propertyName = e.getKey();
            List<DictCode2Name> value = e.getValue();
            return Stream.iterate(0, (i) -> ++i).limit(value.size()).map(i -> {
                DictCode2Name anno = value.get(i);

                String alias = anno.deserializeAlias();
                String nameColumn = StrUtil.toCamelCase(anno.nameColumn());
                String other = propertyName + CommonConstant.DICT_TEXT_SUFFIX + (i == 0 ? "" : String.valueOf(i));
                String firstNonBlank = CharSequenceUtil.firstNonBlank(alias, nameColumn, other);

                return firstNonBlank;
            }).collect(Collectors.toList()).stream();
        }).collect(Collectors.toList());

        Class<?> aClassProxy = ByteBuddyUtil.genChildClass(collect, aClass);
        Object o = aClassProxy.newInstance();

        BeanUtil.copyProperties(obj, o);

        //annoMap.entrySet().stream().map(-> {
        //    String propertyNmae = e.getKey();
        //    Map.Entry<String, List<DictCode2Name>> e1 = e;
        //    return e1;
        //})
        //

        Arrays.stream(declaredFields)
            //过滤静态字段
            .filter(field -> !Modifier.isStatic(field.getModifiers()))

            .filter(field -> {
                Object fieldValue = ReflectUtil.getFieldValue(obj, field);
                boolean isNotEmptyCollection = Collection.class.isAssignableFrom(field.getType()) && CollUtil.isNotEmpty((Collection<?>) fieldValue);
                boolean annotationPresent = field.isAnnotationPresent(DictCode2Name.class) || field.isAnnotationPresent(DictCode2Names.class);
                boolean nonNull = Objects.nonNull(fieldValue);
                return isNotEmptyCollection || annotationPresent && nonNull;
            }).forEach(field -> {
                field.setAccessible(true);
                //让嵌套属性对象支持翻译
                boolean isCollection = Collection.class.isAssignableFrom(field.getType());
                if (isCollection) {
                    Collection fieldValue = (Collection) ReflectUtil.getFieldValue(obj, field);
                    Collection collect2 = (Collection) fieldValue.stream().map(this::transOutVO).collect(Collectors.toList());
                    ReflectUtil.setFieldValue(o, field.getName(), collect2);
                } else {
                    //RefUtil.findAnnoMap(field, DictCode2Name.class, DictCode2Names.class, DictCode2Names::value)
                    DictCode2Name annotation = field.getAnnotation(DictCode2Name.class);
                    if (annotation == null) {
                        DictCode2Names annotation1 = field.getAnnotation(DictCode2Names.class);
                        DictCode2Name[] value = annotation1.value();
                        for (int i = 0; i < value.length; i++) {
                            DictCode2Name dictCode2Name = value[i];

                            String fieldDictValue = String.valueOf(ReflectUtil.getFieldValue(obj, field));

                            String dictCode = Optional.ofNullable(dictCode2Name.value()).filter(StrUtil::isNotBlank).orElse(dictCode2Name.dicCode());
                            String dictAfterName = extractSingleAttributeTranslation(fieldDictValue, dictCode, dictCode2Name.tab(), dictCode2Name.codeColumn(), dictCode2Name.nameColumn(), dictCode2Name.isMulti());
                            String alias = dictCode2Name.deserializeAlias();
                            String nameColumn = StrUtil.toCamelCase(dictCode2Name.nameColumn());
                            String other = field.getName() + CommonConstant.DICT_TEXT_SUFFIX + (i == 0 ? "" : String.valueOf(i));

                            //String other = field.getName() + CommonConstant.DICT_TEXT_SUFFIX;
                            String firstNonBlank = Stream.of(alias, nameColumn, other).filter(StrUtil::isNotBlank).findFirst().orElse("");

                            ReflectUtil.setFieldValue(o, firstNonBlank, dictAfterName);
                        }
                    } else {

                        String fieldDictValue = String.valueOf(ReflectUtil.getFieldValue(obj, field));

                        String dictCode = Optional.ofNullable(annotation.value()).filter(StrUtil::isNotBlank).orElse(annotation.dicCode());
                        String dictAfterName = extractSingleAttributeTranslation(fieldDictValue, dictCode, annotation.tab(), annotation.codeColumn(), annotation.nameColumn(), annotation.isMulti());
                        String alias = annotation.deserializeAlias();
                        String nameColumn = StrUtil.toCamelCase(annotation.nameColumn());
                        String other = field.getName() + CommonConstant.DICT_TEXT_SUFFIX;
                        String firstNonBlank = CharSequenceUtil.firstNonBlank(alias, nameColumn, other);

                        ReflectUtil.setFieldValue(o, firstNonBlank, dictAfterName);
                    }

                }

            });
        return o;
    }

    /**
     * 提取单属性翻译
     *
     * @param fieldRuntimeValue field属性运行时值 Integer或String 入参
     * @param dictCode
     * @param tab
     * @param codeColumn
     * @param nameColumn
     * @param isMulti
     * @return {@link String }
     * @author zjarlin
     * @since 2023/03/25
     */
    private <T> String extractSingleAttributeTranslation(T fieldRuntimeValue, final String dictCode, final String tab, String codeColumn, String nameColumn, final boolean isMulti) {
        if (StrUtil.isAllBlank(dictCode, tab, codeColumn, nameColumn)) {
            return String.valueOf(fieldRuntimeValue);
        }
        String retStr = "";
        String fieldRuntimeStrValue = String.valueOf(fieldRuntimeValue);

        codeColumn = StrUtil.toUnderlineCase(codeColumn);
        nameColumn = StrUtil.toUnderlineCase(nameColumn);
        //dictCode不空 这仨参数全是空说明是内置字典翻译
        boolean isUseSysDefaultDict = StrUtil.isNotBlank(dictCode) && StrUtil.isAllBlank(tab, codeColumn, nameColumn);

        //如果不是内置字典的翻译

        if (!isUseSysDefaultDict) {
            if (!isMulti) {
                retStr = commonAPI.translateDictFromTable(tab, nameColumn, codeColumn, fieldRuntimeStrValue);
            } else {
                //如果是多个用逗号隔开的翻译
                Map<String, String> relation = commonAPI.translateDictFromTableByKeys(tab, nameColumn, codeColumn, fieldRuntimeStrValue).stream().collect(Collectors.toMap(DictModel::getValue, DictModel::getLabel));
                String[] split = fieldRuntimeStrValue.split(",");
                retStr = Arrays.stream(split).map(relation::get).collect(Collectors.joining(","));
            }
        } else {

            if (!isMulti) {
                retStr = commonAPI.translateDict(dictCode, fieldRuntimeStrValue);
            } else {
                Map<String, List<DictModel>> stringListMap = commonAPI.translateManyDict(dictCode, fieldRuntimeStrValue);
                List<DictModel> dictModels = stringListMap.get(dictCode);
                retStr = dictModels.stream().map(DictModel::getLabel).collect(Collectors.joining(","));
            }
        }
        return retStr;
    }

}

